﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace IQIGame.Onigao.Game
{
    public class UIListHelper
    {
        private readonly UIBaseWindow belongWindow;
        private readonly UIBaseNode belongNode;

        private List<IUIList> uiList = null;

        public UIListHelper(UIBaseWindow belongWindow, UIBaseNode belongNode)
        {
            this.belongWindow = belongWindow;
            this.belongNode = belongNode;
        }

        public UIItemPool<T> InitPool<T>(GameObject gobj) where T : UIBaseNode, new()
        {
            UIItemPool<T> ret = new(gobj, this.belongWindow);
            this.AddUIList(ret);
            return ret;
        }

        private void AddUIList(IUIList obj)
        {
            if (this.uiList == null)
                this.uiList = new(8);
            this.uiList.Add(obj);
        }

        /// <summary>
        /// 列表或者滚动的非循环列表
        /// </summary>
        public ListScrollAdapter<T> InitListScroll<T>(GameObject gobj, System.Action<T, int> funcUnitChanged = null) where T : UIBaseNode, new()
        {
            ListScrollAdapter<T> ret = new(gobj, this.belongWindow);
            ret.BindUnitChangedCall(funcUnitChanged);
            this.AddUIList(ret);
            return ret;
        }

        /// <summary>
        /// 滚动的循环列表
        /// </summary>
        public LoopScrollAdapter<T> InitLoopScroll<T>(IExLoopScrollRect scrollRect, System.Action<T, int> funcUnitChanged = null) where T : UIBaseNode, new()
        {
            LoopScrollAdapter<T> ret = new(scrollRect, this.belongWindow);
            ret.BindUnitChangedCall(funcUnitChanged);
            this.AddUIList(ret);
            return ret;
        }

        /// <summary>
        /// 不动态创建子元素的列表(无规则布局的列表)
        /// </summary>
        public IrregularListAdapter<T> InitIrregularList<T>(GameObject gobjRoot, System.Action<T, int> funcUnitChanged = null) where T : UIBaseNode, new()
        {
            IrregularListAdapter<T> ret = new(gobjRoot, this.belongWindow);
            ret.BindUnitChangedCall(funcUnitChanged);
            this.AddUIList(ret);
            return ret;
        }

        public void Clear()
        {
            if (this.uiList == null || this.uiList.Count == 0)
                return;
            for (var i = this.uiList.Count - 1; i >= 0; i--)
            {
                this.uiList[i].Clear();
            }
            this.uiList.Clear();
            this.uiList = null;
        }
    }
}
